<div id="fence-manager" class="full" style="padding: 10px;">
    <div class="demo-spin-container" v-if="loading">
        <Spin size="large" fix></Spin>
    </div>
    <div class="full" style="position: relative;">
        <h3 class="h3-title">{{$t("bgMgr.fenceManager")}}</h3>
        <div style="position: absolute;top: 28px;left: 0;right: 0;height: 35px;">
            <div style="position: absolute;left: 0;top: 0;bottom: 0;width: 300px;line-height: 35px;">{{$t("bgMgr.allAevcieList")}}</div>
            <div style="position: absolute;right:210px;top: 0;bottom: 0;left: 310px;line-height: 35px;">
                {{$t("bgMgr.selectedDeviceList")}} {{tableData.length}}
                <i-button type="error" size="small" @click="tableData=[]" style="float: right;margin-top: 5px;">{{$t("insure.removeAll")}}</i-button>
            </div>
            <div style="position: absolute;right: 0px;top: 0px;bottom: 0px;width: 200px;line-height: 35px;">
                {{$t("bgMgr.systemFenceList")}}
                <i-button type="primary" size="small" @click="jumpSystemFence" style="float: right;margin-top: 5px;">{{$t("bgMgr.systemFence")}}</i-button>
            </div>
        </div>

        <div style="position: absolute;top: 63px;left: 0;right: 0;bottom: 45px;">
            <div style="position: absolute;left: 0;top: 0;bottom: 0;width: 300px;">
                <div class="icon_example" style="text-align: center;">
                    <span class="user_icon"></span><span>{{$t("bgMgr.user")}}</span>
                    <span class="group_icon"></span><span>{{$t("bgMgr.group")}}</span>
                    <span class="device_icon"></span><span>{{$t("bgMgr.ordinaryDev")}}</span>
                    <span class="video_icon"></span><span>{{$t("bgMgr.videoDev")}}</span>
                </div>
                <div style="height: 35px;">
                    <i-input v-model.trim="searchDeviceVal" style="width: 100%;" icon="ios-close-circle-outline" @on-click="cleanValue"></i-input>
                </div>
                <div :style="streeStyle">
                    <ul id="ztree" class="ztree"></ul>
                </div>
            </div>
            <div style="position: absolute;right: 210px;top: 0;bottom: 0;left: 310px;">
                <i-table border ref="table" :columns="columns" :data="tableData" @on-row-dblclick="onDblClick" :height="taleHeight"></i-table>
            </div>
            <div style="position: absolute;right: 0px;top: 0px;bottom: 0px;width: 200px;">
                <Tree :data="treeData" show-checkbox @on-check-change="onFenceCheckChange"></Tree>
            </div>
        </div>

        <div style="position: absolute;left: 0;right: 0;bottom: 0px; height: 45px;padding: 5px;">
            <Row style="border: 1px solid #DCDEE2;padding: 5px;">
                <i-col span="24">
                    <div style="width: 500px;margin: 0 auto;">
                        <Poptip confirm :title="$t('bgMgr.isRemoveExistingFence')" @on-ok="clearGeofence">
                            <i-button style="width: 240px;" type="error">{{$t("bgMgr.clearGeofence")}}</i-button>
                        </Poptip>
                        <i-button style="width: 240px;" type="primary" @click="bindGeoFences">{{$t("bgMgr.bindGeoFences")}}</i-button>
                    </div>
                </i-col>
            </Row>
        </div>
    </div>
</div>
<script>
    vueInstanse = new Vue({
        el: "#fence-manager",
        i18n: utils.getI18n(),
        data: {
            loading: false,
            idx: 0,
            searchDeviceVal: '',
            searchDeviceList: [],
            tableData: [],
            treeData: [],
            mileageRatio: 100,
            columns: [{
                type: 'index',
                width: 60,
            }, {
                title: vRoot.$t('alarm.devName'),
                key: 'devicename'
            }, {
                title: vRoot.$t('alarm.devNum'),
                key: 'deviceid',
            }, {
                title: vRoot.$t("user.grouping"),
                key: 'groupname'
            }, {
                title: vRoot.$t('alarm.action'),
                width: 85,
                render: function(h, params) {
                    return h('Button', {
                        props: {
                            type: 'error',
                            size: 'small'
                        },
                        style: {
                            marginRight: '5px'
                        },
                        on: {
                            click: function() {
                                vueInstanse.tableData.splice(params.index, 1);
                            }
                        }
                    }, vRoot.$t('insure.remove'))
                }
            }, {
                title: vRoot.$t('bgMgr.result'),
                width: 90,
                render: function(h, params) {
                    var result = '',
                        color = '',
                        resultType = params.row.resultType;
                    switch (resultType) {
                        case 0:
                            color = "#2D8CF0";
                            result = vRoot.$t('device.actionSucc');
                            break;
                        case 1:
                            color = "#E4393C";
                            result = vRoot.$t('device.actionFail');
                            break;
                        case 2:
                            color = "#000";
                            result = vRoot.$t('device.notOperated');
                            break;
                        case 3:
                            color = "red";
                            result = vRoot.$t('device.noDevice');
                            break;
                        case 4:
                            color = "red";
                            result = vRoot.$t('device.passwordError');
                            break;
                        case 5:
                            color = "red";
                            result = vRoot.$t('device.abnormalInstructionIssued');
                            break;
                        case 6:
                            color = "red";
                            result = vRoot.$t('monitor.sendCmdNoCache');
                            break;
                        case 7:
                            color = "red";
                            result = vRoot.$t('monitor.sendCmdAlreadyCache');
                            break;
                        case 8:
                            color = "red";
                            result = vRoot.$t('monitor.changePwdSendCmd');
                            break;
                    }
                    return h('span', {
                        style: {
                            color: color
                        }
                    }, result);
                }
            }],

            taleHeight: 100,

        },
        methods: {
            jumpSystemFence: function() {
                var url = 'setfencesystem.html?token=' + token + '&username=' + userName;
                window.open(url);
            },
            onDblClick: function(row) {
                setFence(row.deviceid);
            },
            cleanValue: function() {
                this.searchDeviceVal = '';
            },
            updatedLocalDeviceInfos: function(tableData, forwardid) {
                tableData.forEach(function(item) {
                    var deviceid = item.deviceid;
                    utils.deviceInfos[deviceid].forwardid = forwardid;
                })
            },
            updatedActionState: function(errorrecords) {
                this.tableData.forEach(function(item) {
                    if (errorrecords.indexOf(item.deviceid) != -1) {
                        item.resultType = 1;
                    } else {
                        item.resultType = 0;
                    }
                })
            },
            onCheckChange: function(selectArr) {
                var me = this;
                var tableData = [];
                selectArr.forEach(function(item) {
                    var deviceid = item.deviceid;
                    if (deviceid && !me.isRepeatAddDevice(deviceid)) {
                        var device = utils.deviceInfos[deviceid];
                        var row = deepClone(device);
                        row.resultType = 2;
                        tableData.push(row);
                    }
                })
                this.tableData = this.tableData.concat(tableData);
            },
            onFenceCheckChange: function(arr) {
                this.checkFenceList = arr;
            },
            isRepeatAddDevice: function(deviceid) {
                var relsut = false;
                for (var i = 0; i < this.tableData.length; i++) {
                    var item = this.tableData[i];
                    if (item.deviceid == deviceid) {
                        relsut = true;
                        break;
                    }
                }
                return relsut;
            },
            queryDevicesTree: function() {
                var me = this;
                this.loading = true;
                GlobalOrgan.getInstance().getGlobalOrganData(function(rootuser) {
                    me.loading = false;
                    me.setTreeDataList(rootuser);
                })
            },
            setTreeDataList: function(rootuser) {
                this.treeDeviceList = [this.castUsersTreeToDevicesTree(rootuser, true, false)];
                var me = this;
                this.setting = {
                    check: {
                        enable: true,
                        chkStyle: "checkbox",
                        chkboxType: {
                            "Y": "ps",
                            "N": "ps"
                        }
                    },
                    callback: {
                        onCheck: function(id, ztree) {
                            var checkedNodes = me.zTreeObj.getCheckedNodes();
                            me.onCheckChange(checkedNodes);
                        }
                    }
                };
                this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);


                // this.searchDeviceList = [this.castUsersTreeToDevicesTree(rootuser, true, false)];
                // this.treeDeviceList = deepClone(this.searchDeviceList);
            },
            filtered: function(textStr) {
                function uniq(array) {
                    var temp = [];
                    for (var i = 0; i < array.length; i++) {
                        if (temp.indexOf(array[i]) == -1) {
                            temp.push(array[i]);
                        }
                    }
                    return temp;
                }
                var newArr = [];
                textStr.split("\n").forEach(function(item) {
                    if (item) {
                        newArr.push(item);
                    }
                })
                return uniq(newArr);
            },
            getDeviceListGroups: function(groups, isNeedDevice, username, isNeedRadio) {
                var groupsList = [],
                    me = this;
                if (groups != null) {
                    for (var i = 0; i < groups.length; ++i) {
                        var group = groups[i];
                        var groupObj = {
                            groupid: group.groupid,
                            name: group.groupname,
                            icon: myUrls.viewhost + "zTreeStyle/img/diy/group.svg"
                        }
                        if (isNeedDevice) {
                            groupObj.render = utils.renderGroup;

                        } else {
                            groupObj.totalCount = group.devices.length;
                            groupObj.name = group.groupname + '(' + group.devices.length + ')';
                        }
                        if (isNeedDevice && group.devices) {
                            groupObj.totalCount = group.devices.length;
                            groupObj.children = [];
                            groupObj.name = group.groupname + '(' + group.devices.length + ')';
                            group.devices.forEach(function(device) {
                                groupObj.children.push({
                                    deviceid: device.deviceid,
                                    name: device.devicename,
                                    icon: utils.getzTreeDeviceIcon(device)
                                });
                                utils.deviceInfos[device.deviceid] = {
                                    deviceid: device.deviceid,
                                    devicename: device.devicename,
                                    username: username,
                                    groupid: group.groupid,
                                    groupname: group.groupname,
                                    forwardid: device.forwardid,
                                }
                            });
                        }
                        groupsList.push(groupObj);
                    }
                }

                if (groupsList.length == 0) {
                    groupsList.push({
                        name: 'Default(0)',
                        groupid: 0,
                        totalCount: 0,
                        children: [],
                        icon: myUrls.viewhost + "zTreeStyle/img/diy/group.svg"
                    });
                }
                return groupsList;

            },
            doCastUsersTreeToDevicesTree: function(usersTrees, isNeedDevice, isNeedRadio) {
                var devicesTreeRecord = [];
                if (usersTrees != null && usersTrees.length > 0) {
                    for (var i = 0; i < usersTrees.length; ++i) {
                        var usersTree = usersTrees[i];
                        var username = usersTree.username;
                        var subusers = usersTree.subusers;
                        var currentsubDevicesTreeRecord = {
                            name: username,
                            username: username,
                            nocheck: isNeedRadio,
                            icon: myUrls.viewhost + "zTreeStyle/img/diy/account.svg"
                        };
                        var deviceListGroups = this.getDeviceListGroups(usersTree.groups, isNeedDevice, username, isNeedRadio);
                        if (username != null && subusers != null && subusers.length > 0) {
                            var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice, isNeedRadio);
                            subDevicesTreeRecord = deviceListGroups.concat(subDevicesTreeRecord);
                            currentsubDevicesTreeRecord.children = subDevicesTreeRecord;
                        } else {
                            currentsubDevicesTreeRecord.children = deviceListGroups;

                        }
                        var totalCount = 0;
                        if (currentsubDevicesTreeRecord.children) {
                            for (var j = 0; j < currentsubDevicesTreeRecord.children.length; ++j) {
                                totalCount += currentsubDevicesTreeRecord.children[j].totalCount;
                            }
                        }
                        currentsubDevicesTreeRecord.totalCount = totalCount;
                        currentsubDevicesTreeRecord.name = username + "(" + totalCount + ")";
                        devicesTreeRecord.push(currentsubDevicesTreeRecord);
                    }
                }
                return devicesTreeRecord;
            },
            castUsersTreeToDevicesTree: function(devicesTreeRecord, isNeedDevice, isNeedRadio) {
                var iViewTree = {
                    open: true,
                    nocheck: isNeedRadio,
                    icon: myUrls.viewhost + "zTreeStyle/img/diy/1_open.png"
                };
                if (devicesTreeRecord != null) {
                    var username = devicesTreeRecord.username;
                    var subusers = devicesTreeRecord.subusers;
                    iViewTree.name = username;
                    iViewTree.username = username;
                    var deviceListGroups = this.getDeviceListGroups(devicesTreeRecord.groups, isNeedDevice, username, isNeedRadio);
                    if (username != null && subusers != null && subusers.length > 0) {
                        var subDevicesTreeRecord = this.doCastUsersTreeToDevicesTree(subusers, isNeedDevice, isNeedRadio);
                        iViewTree.children = deviceListGroups.concat(subDevicesTreeRecord);
                    } else {
                        iViewTree.children = deviceListGroups;
                    }
                    var totalCount = 0;
                    if (iViewTree.children) {
                        for (var i = 0; i < iViewTree.children.length; ++i) {
                            totalCount += iViewTree.children[i].totalCount;
                        }
                    }
                    iViewTree.name = username + "(" + totalCount + ")";
                }
                return iViewTree;
            },
            calcTableHeight: function() {
                var wHeight = window.innerHeight;
                if (wHeight < 760) {
                    wHeight = 760;
                }
                this.taleHeight = wHeight - 194;
            },
            queryForwardProtocols: function() {
                var me = this;
                var url = myUrls.queryForwardProtocols();
                utils.sendAjax(url, {}, function(resp) {
                    me.protocols = resp.protocols;
                });
            },
            getRegularPattern: function(str) {
                var res = {};
                // var reg = /^[a-z0-9a-z]{15}/;
                var reg = new RegExp("^[A-Z0-9a-z]{" + this.idLength + "}");
                if (reg.test(str)) {
                    if (str.length > this.idLength) {
                        var newStr = str.slice(this.idLength);
                        var i = 0;
                        var charArray = [];
                        while (true) {
                            var char = newStr[i];
                            var isTrue = /[A-Z0-9a-z]/.test(char);
                            if (!isTrue) {
                                charArray.push(char);
                            } else {
                                break;
                            }
                            i++;
                        };
                        if (charArray.length > 0) {
                            res.errormsg = "OK";
                            res.content = charArray.join("");
                        } else {
                            res.errormsg = "start id error!";
                            res.content = null;
                        }
                    } else {
                        if (str.length == this.idLength) {
                            res.errormsg = "OK";
                            res.content = str;
                        } else {
                            res.errormsg = "start id error!";
                            res.content = null;
                        }
                    }
                } else {
                    res.content = null;
                    res.errormsg = "start id error!";
                }
                return res;
            },

            clearGeofence: function() {
                if (this.tableData.length == 0) {
                    this.$Message.error(vRoot.$t('reportForm.selectDevTip'));
                    return;
                }
                var me = this;
                var data = {
                    deviceids: [],
                    action: 'cleargeofence',
                }
                this.tableData.forEach(function(item) {
                    data.deviceids.push(item.deviceid);
                });
                var url = myUrls.batchOperate();
                me.loading = true;
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    if (respData.status === 0) {
                        if (respData.total == respData.success) {
                            me.$Message.success(vRoot.$t('device.actionSucc'));
                        } else {
                            me.$Message.error(vRoot.$t('message.changeFail') + ' : ' + respData.fail);
                        }
                        me.updatedActionState(respData.errorrecords);
                    } else {
                        me.$Message.error(respData.cause);
                    }
                }, function() {
                    me.loading = false;
                });
            },
            bindGeoFences: function() {
                if (this.tableData.length == 0) {
                    this.$Message.error(vRoot.$t('reportForm.selectDevTip'));
                    return;
                }
                if (this.checkFenceList.length == 0) {
                    this.$Message.error(isZh ? '请选择要添加的围栏' : 'Please select the fence to add');
                    return;
                }
                var me = this;
                var data = {
                    deviceids: [],
                    geosystemcategoryids: [],
                    action: 'bindgeofences',
                }
                me.loading = true;
                this.tableData.forEach(function(item) {
                    data.deviceids.push(item.deviceid);
                });
                this.checkFenceList.forEach(function(item) {
                    if (item.children) {
                        data.geosystemcategoryids.push(item.categoryid);
                    }
                });
                var url = myUrls.batchOperate();
                utils.sendAjax(url, data, function(respData) {
                    me.loading = false;
                    if (respData.status === 0) {
                        if (respData.total == respData.success) {
                            me.$Message.success(vRoot.$t('device.actionSucc'));
                        } else {
                            me.$Message.error(vRoot.$t('message.changeFail') + ' : ' + respData.fail);
                        }
                        me.updatedActionState(respData.errorrecords);
                    } else {
                        me.$Message.error(respData.cause);
                    }
                }, function() {
                    me.loading = false;
                });
            },
            queryGroupInfos: function(callback) {
                var me = this;
                me.allGroups = {};
                utils.sendAjax(myUrls.queryGroupInfos(), {}, function(resp) {
                    if (resp.status === 0) {
                        resp.groups.forEach(function(item) {
                            me.allGroups[item.groupid] = item;
                        });
                    }
                })
            },
            getGroupName: function(groupId) {
                var groupName = "";
                if (this.allGroups[groupId] !== undefined) {
                    groupName = this.allGroups[groupId].groupname;
                }
                return groupName;
            },
            variableDeepSearch: function(treeDataFilter, searchWord, limitcount) {
                var childTemp = [];
                var that = this;
                for (var i = 0; i < treeDataFilter.length; i++) {
                    var copyItem = null;
                    var item = treeDataFilter[i];
                    if (item != null) {

                        var isFound = false;
                        if (item.name.indexOf(searchWord) != -1 || (item.deviceid && item.deviceid.toLowerCase().indexOf(searchWord) != -1)) {
                            copyItem = item;
                            copyItem.open = false;
                            isFound = true;
                        }
                        if (isFound == false && item.children && item.children.length > 0) {
                            // item.expand = true;
                            // childTemp.push(item);
                            var rs = that.variableDeepSearch(item.children, searchWord, limitcount);
                            if (rs && rs.length > 0) {
                                copyItem = deepClone(item);
                                copyItem.children = rs;
                                copyItem.open = true;
                                isFound = true;
                            }
                        }

                        if (isFound == true) {
                            limitcount++;
                            childTemp.push(copyItem);

                            if (limitcount > 1000) {
                                break;
                            }
                        }
                    }
                }

                return childTemp;
            },
            _queryGeoSystemRecords: function() {
                var url = myUrls.queryGeoSystemRecords(),
                    me = this;
                utils.sendAjax(url, {}, function(resp) {
                    if (resp.status == 0) {
                        var categorys = resp.categorys;
                        if (categorys) {
                            categorys.forEach(function(group) {
                                group.title = group.name;
                                group.children = group.records;
                                group.children.forEach(function(item) {
                                    if (isZh) {
                                        item.title = item.name + (item.useas == 0 ? '(进出围栏)' : '(趟数统计)');
                                    } else {
                                        item.title = item.name + (item.useas == 0 ? '(Access fence)' : '(Statistics of trips)');
                                    }
                                    item.disabled = true;
                                })
                            })

                        } else {
                            categorys = [];
                        };
                        me.treeData = categorys;
                    }
                })
            }
        },
        computed: {
            fontColor: function() {
                return [this.isOk ? 'succ' : 'error'];
            },
            streeStyle: function() {
                return {
                    'height': (this.taleHeight - 60) + 'px',
                    'overflow-y': 'auto'
                }
            },
            deviceids: function() {
                var deviceids = [];
                this.tableData.forEach(function(item) {
                    deviceids.push(item.deviceid);
                });
                return deviceids;
            }
        },
        watch: {
            searchDeviceVal: function(newVal) {
                if (newVal === '') {
                    this.treeDeviceList[0].open = true;
                    this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, this.treeDeviceList);
                } else {
                    var limitcount = 0;
                    var data = this.variableDeepSearch(this.treeDeviceList, newVal, limitcount);
                    if (data.length == 0) {
                        data.push({
                            name: isZh ? '无数据' : 'No data',
                            nocheck: true
                        })
                    }
                    this.zTreeObj = $.fn.zTree.init($("#ztree"), this.setting, data);

                }
            }
        },
        mounted: function() {
            var me = this;
            utils.deviceInfos = {};
            this.calcTableHeight();
            this.treeDeviceList = [];
            this.checkFenceList = [];
            window.onresize = function() {
                me.calcTableHeight();
            }
            this.queryDevicesTree();
            this.queryGroupInfos();
            this._queryGeoSystemRecords();
            this.userName = userName;
        },
    })
</script>